package com.masonluo.mlonlinejudge.service.impl;

import com.masonluo.mlonlinejudge.dao.IndexRepository;
import com.masonluo.mlonlinejudge.entity.Index;
import com.masonluo.mlonlinejudge.exceptions.ResourceNotFoundException;
import com.masonluo.mlonlinejudge.mapper.IndexMapper;
import com.masonluo.mlonlinejudge.model.bo.IndexBo;
import com.masonluo.mlonlinejudge.model.bo.SchoolBo;
import com.masonluo.mlonlinejudge.model.param.IndexParam;
import com.masonluo.mlonlinejudge.service.BookService;
import com.masonluo.mlonlinejudge.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

/**
 * @author masonluo
 * @date 2021/2/10 3:42 下午
 */
@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private IndexRepository indexRepository;

    @Autowired
    private IndexMapper indexMapper;

    @Autowired
    private BookService bookService;

    @Override
    public IndexBo createIndex(Integer bookId, String indexName, Integer order) {
        if (!bookService.exist(bookId)) {
            throw new ResourceNotFoundException(String.format("The book [%d] does not exist", bookId));
        }
        Index idx = new Index();
        idx.setName(indexName);
        idx.setOrder(order);
        idx.setBookId(bookId);
        indexRepository.insert(idx);
        return indexMapper.doToBo(idx);
    }

    @Override
    public List<IndexBo> listByBookId(Integer bookId, boolean order) {
        List<Index> doList = indexRepository.listByBookId(bookId);
        List<IndexBo> boList = indexMapper.doToBo(doList);
        if (order) {
            boList.sort(Comparator.comparingInt(IndexBo::getOrder));
        }
        return boList;
    }

    @Override
    public List<IndexBo> listBySchoolId(Integer schoolId, boolean order) {
        List<Index> doList = indexRepository.listBySchoolId(schoolId);
        List<IndexBo> boList = indexMapper.doToBo(doList);
        if (order) {
            boList.sort(Comparator.comparingInt(IndexBo::getOrder));
        }
        return boList;
    }

    @Override
    public boolean exist(Integer id) {
        return indexRepository.countById(id) > 0;
    }

    @Override
    public List<IndexBo> listAll() {
        List<Index> indexList = indexRepository.listAll();
        List<IndexBo> boList = indexMapper.doToBo(indexList);
        boList.sort(Comparator.comparingInt(IndexBo::getOrder));
        return boList;
    }

    @Override
    public void deleteById(Integer indexId) {
        indexRepository.deleteById(indexId);
    }

    @Override
    public int update(IndexParam param) {
        return indexRepository.update(param);
    }


}
